<template>
  <div class="user_info_item">
    <div class="content">
      <router-link :to="`/u/${user.domain}`">
        <a-avatar class="avatar" :size="45" :src="user.avatar"/>
      </router-link>
      <div class="info">
        <router-link :to="`/u/${user.domain}`">
          <span class="name" :style="{color:!user.isOwner?'#000000':''}" v-html="user.name"></span>
        </router-link>
        <a-space class="other_info" v-if="!user.isOwner">
          <span>博客</span>
          <span>{{ user.blogTotal }}</span>
          <span>|</span>
          <span>关注</span>
          <span>{{ user.following }}</span>
          <span>|</span>
          <span>粉丝</span>
          <span>{{ user.followers }}</span>
        </a-space>
      </div>
    </div>
    <div class="operation" v-if="!user.isOwner">
      <a-button type="primary" size="small" v-show="!user.isFollow" :loading='followLoading' @click="changeFollow">
        关注
      </a-button>
      <a-button type="primary" size="small" v-show="user.isFollow" :loading='followLoading' @click="changeFollow">
        已关注
      </a-button>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs } from 'vue'
import { Follow, UnFollow } from '@/service/operate'

export default defineComponent({
  props: {
    user: {
      type: Object,
      default () {
        return {
          id: '',
          name: '',
          domain: '',
          introduction: '',
          avatar: '',
          blogTotal: 0,
          followers: 0,
          following: 0,
          isOwner: false,
          isFollow: false
        }
      }
    }
  },
  setup (props) {
    const state = reactive({
      followLoading: false,
      user: props.user
    })

    const methods = reactive({
      changeFollow: async () => {
        state.followLoading = true
        if (state.user.isFollow) {
          await UnFollow(state.user.id)
          state.user.followers -= 1
        } else {
          await Follow(state.user.id)
          state.user.followers += 1
        }
        state.user.isFollow = !state.user.isFollow
        state.followLoading = false
      }
    })

    return {
      ...toRefs(state),
      ...toRefs(methods)
    }
  }
})
</script>

<style lang="less" scoped>
.user_info_item {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  & .content {
    display: flex;
    align-items: center;

    & .info {
      margin-left: 15px;
      display: flex;
      flex-direction: column;

      & .name {
        font-size: 14px;
      }

      & .other_info {
        font-size: 12px;
        opacity: 0.6;
      }
    }
  }
}
</style>
